<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useTaskStore, type Task, type TaskStatus } from '@/stores';
import TaskProgressCircle from '@/components/TaskProgressCircle.vue';

const route = useRoute();
const taskStore = useTaskStore();
const extcode = computed(() => route.params.code as string);
const loading = ref(true);
const error = ref<string | null>(null);

// 当前选中的任务类型
const selectedTaskType = ref<'pending' | 'processing' | 'completed'>('pending');

// 确认弹窗状态
const showConfirmDialog = ref(false);
const confirmAction = ref<() => void>(() => {});
const confirmMessage = ref('');
const confirmTitle = ref('');

// 下拉菜单状态
const openDropdownIndex = ref<number | null>(null);

// 分页相关状态
const currentPage = ref({
  pending: 1,
  processing: 1,
  completed: 1
});
const pageSize = 20;

// 任务详情状态
const selectedTask = ref<Task | null>(null);
const showTaskDetail = ref(false);

// 按状态过滤任务
const pendingTasks = computed(() => {
  return taskStore.tasks
    .filter(task => task.extcode === extcode.value && task.status === 'pending')
    .slice(0, 20);
});

const processingTasks = computed(() => {
  return taskStore.tasks
    .filter(task => task.extcode === extcode.value && task.status === 'processing')
    .slice(0, 20);
});

const completedTasks = computed(() => {
  return taskStore.tasks
    .filter(task => task.extcode === extcode.value && task.status === 'completed')
    .slice(0, 20);
});

// 获取当前显示的任务列表
const currentTasks = computed(() => {
  switch (selectedTaskType.value) {
    case 'pending':
      return pendingTasks.value;
    case 'processing':
      return processingTasks.value;
    case 'completed':
      return completedTasks.value;
  }
});

// 获取任务数据
async function fetchData() {
  loading.value = true;
  error.value = null;
  try {
    await taskStore.fetchTasks();
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取数据失败';
  } finally {
    loading.value = false;
  }
}

// 显示确认弹窗
function showConfirm(title: string, message: string, action: () => void) {
  confirmTitle.value = title;
  confirmMessage.value = message;
  confirmAction.value = action;
  showConfirmDialog.value = true;
}

// 执行确认操作
function handleConfirm() {
  confirmAction.value();
  showConfirmDialog.value = false;
}

// 取消确认操作
function handleCancel() {
  showConfirmDialog.value = false;
}

// 切换下拉菜单
function toggleDropdown(index: number) {
  if (openDropdownIndex.value === index) {
    openDropdownIndex.value = null;
  } else {
    openDropdownIndex.value = index;
  }
}

// 更新任务状态
async function updateStatus(taskId: string, newStatus: TaskStatus) {
  await taskStore.updateTaskStatus(taskId, newStatus);
}

// 删除任务（从列表中移除）
function removeTask(taskId: string) {
  showConfirm(
    '确认删除',
    '确定要从列表中删除此任务吗？',
    async () => {
      const index = taskStore.tasks.findIndex(t => t.id === taskId);
      if (index !== -1) {
        taskStore.tasks.splice(index, 1);
      }
    }
  );
}

// 取消处理任务
function cancelProcessing(taskId: string) {
  showConfirm(
    '取消处理',
    '确定要取消处理此任务吗？',
    () => updateStatus(taskId, 'pending')
  );
}

// 终止完成任务
function completeTask(taskId: string) {
  showConfirm(
    '终止完成',
    '确定要将此任务标记为已完成吗？',
    () => updateStatus(taskId, 'completed')
  );
}

// 继续处理任务
function continueProcessing(taskId: string) {
  showConfirm(
    '继续处理',
    '确定要继续处理此任务吗？',
    () => updateStatus(taskId, 'processing')
  );
}

// 检查任务详情
function inspectTask(task: Task) {
  selectedTask.value = task;
  showTaskDetail.value = true;
}

// 关闭任务详情
function closeTaskDetail() {
  showTaskDetail.value = false;
  selectedTask.value = null;
}

// 下载资源
function downloadResource(taskId: string) {
  console.log('下载任务资源:', taskId);
}

// 获取行样式类名
function getRowClassName(status: TaskStatus) {
  switch (status) {
    case 'pending':
      return 'pending';
    case 'processing':
      return 'processing';
    case 'completed':
      return 'completed';
    default:
      return '';
  }
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

onMounted(() => {
  fetchData();
});

// 当路由参数变化时重新获取数据
watch(() => route.params.code, () => {
  fetchData();
});
</script>

<template>
  <div class="extcode-container">
    <!-- <h2 class="page-title">{{ extcode }} 任务管理</h2> -->
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载任务数据中...</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="fetchData" class="btn btn-primary">重试</button>
    </div>
    
    <!-- 任务管理界面 -->
    <div v-else class="task-management-container">
      <!-- 左侧导航栏 -->
      <div class="task-nav">
        <div class="task-stats">
          <TaskProgressCircle
            :pending="pendingTasks.length"
            :processing="processingTasks.length"
            :completed="completedTasks.length"
            :total="pendingTasks.length + processingTasks.length + completedTasks.length"
          />
        </div>
        <div 
          class="nav-item"
          :class="{ active: selectedTaskType === 'pending' }"
          @click="selectedTaskType = 'pending'"
        >
          待处理 ({{ pendingTasks.length }})
        </div>
        <div 
          class="nav-item"
          :class="{ active: selectedTaskType === 'processing' }"
          @click="selectedTaskType = 'processing'"
        >
          处理中 ({{ processingTasks.length }})
        </div>
        <div 
          class="nav-item"
          :class="{ active: selectedTaskType === 'completed' }"
          @click="selectedTaskType = 'completed'"
        >
          已完成 ({{ completedTasks.length }})
        </div>
      </div>
      
      <!-- 右侧任务列表 -->
      <div class="task-list-container">
        <div class="task-list-header">
          <!-- <h2>{{ selectedTaskType === 'pending' ? '待处理' : selectedTaskType === 'processing' ? '处理中' : '已完成' }}</h2> -->
          <div class="task-header">
            <span class="task-id">TaskID</span>
            <span class="product-name">品名</span>
            <span class="status">状态</span>
            <span class="action">操作</span>
          </div>
        </div>
        <div class="task-list">
          <div v-if="currentTasks.length === 0" class="empty-list">暂无任务</div>
          <div 
            v-for="(task, index) in currentTasks" 
            :key="task.id"
            class="task-row"
            :class="getRowClassName(task.status)"
          >
            <span class="task-id">{{ task.id }}</span>
            <span class="product-name">{{ task.title || `任务 ${task.id}` }}</span>
            <span class="status">
              {{ task.status === 'pending' ? '待处理' : task.status === 'processing' ? '处理中' : '已完成' }}
            </span>
            <span class="action">
              <template v-if="selectedTaskType === 'pending'">
                <div class="action-buttons">
                  <button @click="removeTask(task.id)" class="action-button delete">取消处理</button>
                  <!-- <button @click="completeTask(task.id)" class="action-button terminate">终止</button> -->
                  <button @click="inspectTask(task)" class="action-button">检查</button>
                </div>
              </template>
              
              <template v-else-if="selectedTaskType === 'processing'">
                <div class="action-buttons">
                  <!-- <button @click="removeTask(task.id)" class="action-button delete">删除</button> -->
                  <button @click="cancelProcessing(task.id)" class="action-button cancel">暂停处理</button>
                  <button @click="completeTask(task.id)" class="action-button terminate">终止完成</button>
                  <button @click="inspectTask(task)" class="action-button">检查</button>
                </div>
              </template>
              
              <template v-else>
                <button @click="continueProcessing(task.id)" class="action-button continue">继续处理</button>
                <button class="option-button" @click="toggleDropdown(index)">
                  Option ▼
                </button>
                <div v-if="openDropdownIndex === index" class="dropdown-menu">
                  <button class="dropdown-item" @click="downloadResource(task.id)">下载图片</button>
                  <button class="dropdown-item" @click="inspectTask(task)">查看prompt</button>
                </div>
              </template>
            </span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 任务详情弹窗 -->
    <div v-if="showTaskDetail && selectedTask" class="task-detail-overlay">
      <div class="task-detail">
        <div class="task-detail-header">
          <h3>任务详情</h3>
          <button class="close-button" @click="closeTaskDetail">×</button>
        </div>
        <div class="task-detail-content">
          <div class="detail-item">
            <span class="label">任务ID:</span>
            <span class="value">{{ selectedTask.id }}</span>
          </div>
          <div class="detail-item">
            <span class="label">品名:</span>
            <span class="value">{{ selectedTask.title || `任务 ${selectedTask.id}` }}</span>
          </div>
          <div class="detail-item">
            <span class="label">状态:</span>
            <span class="value status-tag" :class="getRowClassName(selectedTask.status)">
              {{ selectedTask.status === 'pending' ? '待处理' : selectedTask.status === 'processing' ? '处理中' : '已完成' }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDate(selectedTask.createdAt) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">更新时间:</span>
            <span class="value">{{ formatDate(selectedTask.updatedAt) }}</span>
          </div>
          <div class="detail-item description">
            <span class="label">描述:</span>
            <span class="value">{{ selectedTask.description || '暂无描述' }}</span>
          </div>
          <div class="detail-item keywords" v-if="selectedTask.keywords">
            <span class="label">关键词:</span>
            <div class="keyword-list">
              <span 
                v-for="(value, key) in selectedTask.keywords" 
                :key="key"
                class="keyword-tag"
              >
                {{ key }}: {{ value }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 确认弹窗 -->
    <div v-if="showConfirmDialog" class="confirm-dialog-overlay">
      <div class="confirm-dialog">
        <h3>{{ confirmTitle }}</h3>
        <p>{{ confirmMessage }}</p>
        <div class="confirm-dialog-buttons">
          <button @click="handleConfirm" class="confirm-button">确认</button>
          <button @click="handleCancel" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import './styles.css';

.extcode-container {
  padding: 0 0;  
}

.page-title {
  /* margin-bottom: 2rem; */
  color: var(--text-primary);
  font-size: 1.75rem;
  text-align: center;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  text-align: center;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid var(--bg-tertiary);
  border-top-color: var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.task-management-container {
  display: flex;
  gap: 2rem;
  padding: 1rem;
  height: calc(100vh - 110px);
}

.task-nav {
  width: 200px;
  flex-shrink: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.task-stats {
  padding: 0.75rem 0.5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom: 1px solid #eee;
  margin-bottom: 0.5rem;
}

.nav-item {
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #eee;
  position: relative;
  z-index: 1;
}

.nav-item:hover {
  background-color: #f5f5f5;
}

.nav-item.active {
  background-color: var(--primary-color);
  color: white;
}

.task-list-container {
  flex: 1;
  min-width: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

.empty-list {
  padding: 1rem;
  text-align: center;
  color: var(--text-secondary);
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: var(--border-radius-sm);
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover {
  background-color: var(--primary-color-dark);
  transform: translateY(-1px);
}

.btn-secondary {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.btn-secondary:hover {
  background-color: var(--bg-quaternary);
  transform: translateY(-1px);
}

/* 任务详情弹窗样式 */
.task-detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.task-detail {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  animation: slideIn 0.3s ease-out;
}

.task-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.task-detail-header h3 {
  margin: 0;
  color: var(--text-primary);
}

.close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--text-secondary);
}

.task-detail-content {
  padding: 1rem;
}

.detail-item {
  margin-bottom: 1rem;
  display: flex;
}

.detail-item .label {
  font-weight: bold;
  width: 100px;
  flex-shrink: 0;
  color: var(--text-secondary);
}

.detail-item .value {
  flex: 1;
  color: var(--text-primary);
}

.detail-item.description {
  flex-direction: column;
}

.detail-item.description .value {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background-color: #f9f9f9;
  border-radius: 4px;
  white-space: pre-wrap;
}

.detail-item.keywords {
  flex-direction: column;
}

.keyword-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.keyword-tag {
  background-color: #f0f0f0;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
}

.status-tag {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  color: white;
}

.status-tag.pending {
  background-color: var(--pending-color);
}

.status-tag.processing {
  background-color: var(--processing-color);
}

.status-tag.completed {
  background-color: var(--completed-color);
}
</style>